package com.dingreading.cloud.soms.controller;

import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.FileUtil;
import com.dingreading.cloud.common.util.KitUtil;
import com.dingreading.cloud.common.util.aliyun.OSSClientUtil;
import com.dingreading.cloud.common.util.aliyun.OssStsDto;
import com.dingreading.cloud.soms.util.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping("/system/upload")
@Api(tags = "阿里云-上传文件")
public class OssUploadController {

    @Resource
    private RedisService redisService;

    public static final String readerContestDir = "soms/readercontest/";
    public static final String callNameImgDir = "soms/callnameimg/";


    @ApiOperation(value = "门店-获取上传公共bucket的临时授权信息(门店端上传跟进记录图片)")
    @PostMapping(value = "/getBucketOssCreditByFollowImg", produces = "application/json; charset=UTF-8")
    public R<Object> getBucketOssCreditByFollowImg(
            @ApiParam(value = "文件的类型") @RequestParam(value = "fileType") String fileType
    ) {
        if (!fileType.equals("jpg") && !fileType.equals("png") && !fileType.equals("jpeg"))
            return R.fail("图片类型只能选择jpg、png、jpeg");

        OSSClientUtil ossClientUtil = new OSSClientUtil();
        // 获取上传路径
        String todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.storeFollowImgDir);

        if (StringUtils.isBlank(todayDir))
            return R.fail("获取阿里云上传路径失败");

        // 获取 随机名称.文件类型
        String fileName = KitUtil.getUuid() + "." + fileType;
        if (StringUtils.isBlank(fileName))
            return R.fail("生成文件名失败");

        // 获取redis里的临时授权信息
        String securityToken = (String) redisService.get(OSSClientUtil.STS_SECURITYTOKEN);
        String accessKeyId = (String) redisService.get(OSSClientUtil.STS_ACCESSKEYID);
        String accessKeySecret = (String) redisService.get(OSSClientUtil.STS_ACCESSKEYSECRET);
        String expiration = (String) redisService.get(OSSClientUtil.STS_EXPIRATION);
        if (StringUtils.isBlank(securityToken) || StringUtils.isBlank(accessKeyId) || StringUtils.isBlank(accessKeySecret)) {
            // 重新获取阿里云的临时授权信息
            AssumeRoleResponse.Credentials response = ossClientUtil.getAssumeRoleResponse();
            if (response == null) return R.fail("获取阿里云STS授权失败");

            securityToken = response.getSecurityToken();
            accessKeyId = response.getAccessKeyId();
            accessKeySecret = response.getAccessKeySecret();
            expiration = response.getExpiration();
        }
        String region = OSSClientUtil.region;
        String publicBucket = OSSClientUtil.publicBucket;

        OssStsDto dto = new OssStsDto();
        dto.setAccessKeyId(accessKeyId);
        dto.setAccessKeySecret(accessKeySecret);
        dto.setSecurityToken(securityToken);
        dto.setRegion(region);
        dto.setBucket(publicBucket);
        dto.setFileName(todayDir.concat(fileName));
        dto.setExpiration(expiration);
        return R.ok(dto);
    }

    @ApiOperation(value = "上传图片")
    @PostMapping(value = "/image", produces = "application/json; charset=UTF-8")
    public R<Object> image(
            @ApiParam(value = "图片文件") @RequestPart(value = "image") MultipartFile multipartFile,
            @ApiParam(value = "平台类型 1.管理 2.加盟商 3.移动端 4.合同 5.商城") @RequestParam(value = "type") Integer type
    ) {
        boolean m = FileUtil.checkFileSize(multipartFile.getSize(), 5, "M");
        if (!m) return R.fail("上传图片大小不能超过5M");

        OSSClientUtil ossClientUtil = new OSSClientUtil();
        ossClientUtil.initOss();

        String todayDir = "";

        if (type.equals(1)) {
            todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.systemDir);
        } else if (type.equals(2)) {
            todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.storeDir);
        } else if (type.equals(3)) {
            todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.mobileDir);
        } else if (type.equals(4)) {
            todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.contractDir);
        } else if (type.equals(5)) {
            todayDir = ossClientUtil.getTodaySplitDir(OSSClientUtil.mallDir);
        } else {
            return R.fail("平台类型错误");
        }

        String resultUrl = ossClientUtil.uploadImg2Oss(todayDir, multipartFile);
        ossClientUtil.destory();
        if (StringUtils.isBlank(resultUrl)) {
            return R.fail("上传图片失败");
        }
        return R.ok(todayDir + resultUrl);
    }

    @ApiOperation(value = "门店-获取上传公共bucket的临时授权信息")
    @PostMapping(value = "/getBucketOssCredit", produces = "application/json; charset=UTF-8")
    public R<Object> getBucketOssCredit(
            @ApiParam(value = "文件的类型") @RequestParam(value = "fileType") String fileType,
            @ApiParam(value = "上传的文件目录：导读教学大赛:readercontest") @RequestParam(value = "fileDir") String fileDir
    ) {
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        // 获取上传路径
        String todayDir = "";
        if (fileDir.contains("readercontest")) {
            todayDir = ossClientUtil.getTodaySplitDir(readerContestDir);
        } else if (fileDir.contains("callnameimg")) {
            todayDir = ossClientUtil.getTodaySplitDir(callNameImgDir);
        } else {
            return R.fail("上传的文件目录不存在");
        }

        if (StringUtils.isBlank(todayDir))
            return R.fail("获取阿里云上传路径失败");

        // 获取 随机名称.文件类型
        String fileName = KitUtil.getUuid() + "." + fileType;
        if (StringUtils.isBlank(fileName))
            return R.fail("生成文件名失败");

        // 获取redis里的临时授权信息
        String securityToken = (String) redisService.get(OSSClientUtil.STS_SECURITYTOKEN);
        String accessKeyId = (String) redisService.get(OSSClientUtil.STS_ACCESSKEYID);
        String accessKeySecret = (String) redisService.get(OSSClientUtil.STS_ACCESSKEYSECRET);
        String expiration = (String) redisService.get(OSSClientUtil.STS_EXPIRATION);
        if (StringUtils.isBlank(securityToken) || StringUtils.isBlank(accessKeyId) || StringUtils.isBlank(accessKeySecret)) {
            // 重新获取阿里云的临时授权信息
            AssumeRoleResponse.Credentials response = ossClientUtil.getAssumeRoleResponse();
            if (response == null) return R.fail("获取阿里云STS授权失败");

            securityToken = response.getSecurityToken();
            accessKeyId = response.getAccessKeyId();
            accessKeySecret = response.getAccessKeySecret();
            expiration = response.getExpiration();
        }
        String region = OSSClientUtil.region;
        String publicBucket = OSSClientUtil.publicBucket;

        OssStsDto dto = new OssStsDto();
        dto.setAccessKeyId(accessKeyId);
        dto.setAccessKeySecret(accessKeySecret);
        dto.setSecurityToken(securityToken);
        dto.setRegion(region);
        dto.setBucket(publicBucket);
        dto.setFileName(todayDir.concat(fileName));
        dto.setExpiration(expiration);
        return R.ok(dto);
    }

}
